package com.hhf.rpc.feirpcspringbootstarter.bootstrap;

import com.hhf.rpc.core.RpcApplication;
import com.hhf.rpc.core.config.RegistryConfig;
import com.hhf.rpc.core.config.RpcConfig;
import com.hhf.rpc.core.model.ServiceMetaInfo;
import com.hhf.rpc.core.model.ServiceRegisterInfo;
import com.hhf.rpc.core.registry.LocalRegistry;
import com.hhf.rpc.core.registry.Registry;
import com.hhf.rpc.core.registry.RegistryFactory;
import com.hhf.rpc.core.server.impl.VertxTcpServer;
import com.hhf.rpc.feirpcspringbootstarter.annotation.RpcService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.util.List;

/**
 * @Author hhf
 * @Date 2024/10/20
 * @Description 服务提供者初始化
 */
public class ProviderBootstrap implements BeanPostProcessor {


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        Class<?> beanClass = bean.getClass();
        RpcService rpcService = beanClass.getAnnotation(RpcService.class);

        if (rpcService != null){
            //需要注册的服务
            //1.获取服务基本信息
            Class<?> interfaceClass = rpcService.interfaceClass();
            //默认值处理
            if (interfaceClass == void.class){
                interfaceClass = beanClass.getInterfaces()[0];
            }
            String serviceName = interfaceClass.getName();
            String serviceVersion = rpcService.serviceVersion();
            //2.注册服务
            //注册服务
            //本地注册---存储信息,用于寻找实现类
            LocalRegistry.register(serviceName, beanClass);

            //注册中心注册---用于远程调用
            final RpcConfig rpcConfig = RpcApplication.getRpcConfig();

            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getRegistry(registryConfig.getRegistry());
            //构建服务Info对象
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceVersion(serviceVersion);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName + "服务注册失败", e);
            }

        }


        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
